package com.xx.jfb.tomcat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.SocketException;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @author xuyuanpeng
 * @version 1.0
 * @date 2019-06-27 10:27
 */
public class MiniTomcat {

    private ServerSocketChannel ssc;

    private ThreadPoolTaskConfig pool;

    public static void main(String[] args)throws Exception {
        new MiniTomcat().start();
    }


    public void start()throws Exception{
        try {
            create();
            channel();
        }catch (Exception e){
            throw new Exception(e.getMessage());
        }
    }

    /**
     * 建立socket链接
     * @throws SocketException
     */
    public void create()throws SocketException {
        try {

            ssc = ServerSocketChannel.open();
            ssc.configureBlocking(false);
            ServerSocket serverSocket = ssc.socket();
            serverSocket.bind(new InetSocketAddress(10001));
            //线程池处理请求
            pool = new ThreadPoolTaskConfig(200);

        }catch (SocketException e){
            throw new SocketException("create socket is error !");
        }catch (IOException e){
            throw new SocketException("io is error !");
        }
    }

    /**
     * 线程池处理请求
     * @throws Exception
     */
    public void channel()throws Exception{
        while (true){
            try{
                //获得请求
                SocketChannel channel = ssc.accept();
                //新建线程处理请求
                if(null != channel){
                    pool.getExecutor().execute(new HttpHandle(channel));
                }
            }catch (IOException e){
                throw new IOException(" accept is error !");
            }
        }
    }
}

